package com.jdkreader.concurrency.concurrent;


import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * 同步计数器CountDownLatch示例
 *
 */
public class SummonDragonDemo {

    //集齐七颗龙珠召唤神龙
    private static final int THREAD_COUNT_SUM = 7;

    private static CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT_SUM);

    public static void main(String[] args) throws InterruptedException{

        for(int i=1;i<=THREAD_COUNT_SUM;i++){
            int index=i;
            new Thread(() ->{
                 try{
                     System.out.println("第"+index+"颗龙珠已经找到");
                     //模拟寻找龙珠的时间
                     Thread.sleep(new Random().nextInt(3000));
                 }catch(InterruptedException e){
                     e.printStackTrace();
                 }
                 //每收集一颗龙珠，计数减一
                 countDownLatch.countDown();
            }).start();
        }
        //等待计数归零
        countDownLatch.await();
        System.out.println("龙珠已经集齐，可以召唤神龙了。");

    }

}
